package database.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


import database.pojo.PlayerCollectSongInfo;

public class PlayerCollectSongInfoDao{
	public boolean insert(PlayerCollectSongInfo pInfo, Connection conn ) throws SQLException {
		
		String sqlInsert = "insert into PlayerCollectSong(openId, songId) values( ? , ? )";
		PreparedStatement pstmt = null;
		boolean result = true;
		try{
			pstmt = conn.prepareStatement(sqlInsert);//相当于python操作数据库的游标
			pstmt.setString(1, pInfo.getOpenId());
			pstmt.setString(2, pInfo.getSongId());
			pstmt.executeUpdate();
		}catch (Exception e) {
			System.out.println(" insert Exception" + e);
			result = false;
		}
		finally{
			if(pstmt != null){
				pstmt.close();
			}
		}
		return result;
		
	}
	
	
	public boolean delete(String openId,String songId, Connection conn ) throws SQLException {
		String sqlDelete = "delete  from PlayerCollectSong where openId = ? and songId = ?";
		PreparedStatement pstmt = null;
		boolean result = true;
		try{
			pstmt = conn.prepareStatement(sqlDelete);//相当于python操作数据库的游标
			pstmt.setString(1, openId);
			pstmt.setString(2, songId);
			//System.out.println("delect---getsongId"+songId);
			pstmt.executeUpdate();
		}catch (Exception e) {
			System.out.println(" delect Exception" + e);
			result = true;
		}
		finally{
			if(pstmt != null){
				pstmt.close();
			}
		}
		return result;
		
	}
	
	
	public PlayerCollectSongInfo update(PlayerCollectSongInfo pInfo , Connection conn) throws SQLException {
		
		String sqlUpdate = "update PlayerCollectSong set songId = ? where openId = ?";
		PreparedStatement pstmt = null;
		
		try {
			pstmt = conn.prepareStatement(sqlUpdate);
			pstmt.setString(2, pInfo.getOpenId());
			pstmt.setString(1, pInfo.getSongId());
			pstmt.executeUpdate();
			
		}catch (Exception e) {
			System.out.println(" update Exception" + e);
		} 
		finally {
			if(pstmt != null) {
				pstmt.close();
			}
		}
		return pInfo;
		
	}
	
	
	public ArrayList<PlayerCollectSongInfo> selectAllByOpenId(String openId,Connection conn) throws SQLException {
		String sqlSelect = "select * from PlayerCollectSong where openId = ? ";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ArrayList<PlayerCollectSongInfo> pinfoList = new ArrayList<PlayerCollectSongInfo>();
		PlayerCollectSongInfo pInfo = null;
		System.out.println("get open id " + openId);
		try{
			pstmt = conn.prepareStatement(sqlSelect);
			pstmt.setString(1, openId);
			rs = pstmt.executeQuery();
			while(rs.next()){
				//System.out.println("selectAllByopenId-------songId--"+rs.getString("songId"));
				pInfo =new PlayerCollectSongInfo();
				pInfo.setOpenId(rs.getString("openId"));
				pInfo.setSongId(rs.getString("songId"));
				pinfoList.add(pInfo);
				}
			}finally {
				if(pstmt != null){
					pstmt.close();
				}
			}
		
		return pinfoList;
	}
}